<!--
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2024-11-11 15:21:33
 * @LastEditTime: 2024-11-11 17:56:05
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 
 * @FilePath: \markdown-magic\src\pages\Pdf\page\entry\unlock.vue
 * Copyright 版权声明
-->
<template>
  <div class="pageWrap">
    <div class="descArea">
      只需上传文档等等数秒即可轻松删除PDF密码保护进行PDF解密，支持批量删除密码，便于你后续阅读或编辑文档。
      <br />
      <span style="color: #f00;text-decoration: underline;">注意：本功能不是破解密码是移除原有的密码需要提供原密码无法实现破解PDF密码功能。</span>
    </div>
    <a-upload-dragger
      v-model:fileList="fileList"
      accept=".pdf,.PDF"
      name="file"
      :maxCount="1"
      :multiple="true"
      :showUploadList="true"
      action=""
      :before-upload="beforeUpload"
      :customRequest="customRequest"
      list-type="picture"
      @change="handleChange"
      @drop="handleDrop"
      @remove="handleRemove"
    >
      <p class="ant-upload-drag-icon">
        <inbox-outlined></inbox-outlined>
      </p>
      <p class="ant-upload-text">点击选择或拖拽文件到这里上传</p>
      <p class="ant-upload-hint">
        可上传1个PDF文件，单个不超过10MB（拖拽调整顺序）
      </p>
    </a-upload-dragger>
    <div class="inputArea">
      
      <a-form
        :model="formData"
        name="basic"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        layout="inline"
      >
        <a-form-item
          label="解锁密码："
          name="password"
          :rules="[{ required: true, message: 'Please input your password!' }]"
        >
          <a-input
            v-model:value="formData.password"
            placeholder="请输入原密码"
            type="password"
            style="width: 250px;"
          />
        </a-form-item>
      </a-form>
    </div>
    <div class="btnsWrap">
      <a-space>
        <a-button type="primary" @click="handleProcess"><PlayCircleOutlined />开始处理</a-button>
        <a-button v-if="mergedPdf" danger @click="handleClear"><ClearOutlined />清空文件</a-button>
        <a-button v-if="mergedPdf" type="primary" ghost @click="handleDownload"><DownloadOutlined />下载</a-button>
      </a-space>
    </div>
    <!-- <pre id="output"></pre> -->
  </div>
</template>

<script setup>
import { ref, reactive, defineEmits } from 'vue'
import { message } from 'ant-design-vue'
import { PlayCircleOutlined, FilePdfOutlined, DownloadOutlined, ClearOutlined } from '@ant-design/icons-vue'
import { PDFDocument } from 'pdf-lib'

import { unlockAndProcessPdf } from '../../service/unlock.js'

import { downloadPdf } from '@/utils/index.js'

const emit = defineEmits([])

const formData = reactive({
  password: ''
})

const fileList = ref([])

const mergedPdf = ref(null)

const handleRemove = (file) => {
  return true
}

const handleChange = (info) => {
  const status = info.file.status
  if (status === 'uploading') {
  } else if (status === 'done') {
    message.success(`${info.file.name} 文件上传成功.`)
  } else if (status === 'error') {
    message.error(`${info.file.name} 文件上传错误.`)
  } else if (status === 'removed') {
    message.error(`${info.file.name} 文件删除成功.`)
  }
}
const handleDrop = (e) => {
  console.log(e)
}

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'application/pdf';
  if (!isJpgOrPng) {
    message.error('请上传pdf格式的文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 1000;
  if (!isLt2M) {
    message.error('文件必须小于1000MB!');
  }
  // fileList.value.splice(0, 1)
  return isJpgOrPng && isLt2M;
}

// 自定义上传
const customRequest = async ({ action, file, onSuccess, onError }) => {
  fileList.value.find(item => {
    if (item.uid === file.uid) {
      item.status = 'done'
    }
    return item.uid === file.uid
  })
}

// 开始处理
const handleProcess = async () => {
  if (!fileList.value.length) {
    message.warning('请上传至少一个pdf文件!')
    return
  }

  // 遍历文件列表
  for (const item of fileList.value) {
    console.log(`🚀 ~ handleProcess ~ item:`, item)

    // 读取文件内容为二进制
    const reader = new FileReader()

    reader.onload = async (e) => {
      const arrayBuffer = e.target.result
      const result = await unlockAndProcessPdf(arrayBuffer, formData.password)
      if (result?.code === 1) {
        message.warning(result?.message)
      } else {
        mergedPdf.value = result
        message.success('处理完成!')
      }
    }

    reader.onerror = (error) => {
      console.error('Error reading the file:', error)
    }

    // 读取文件内容为二进制字符串
    reader.readAsArrayBuffer(item.originFileObj)
  }

}

// 清空文件
const handleClear = () => {
  fileList.value = []
  mergedPdf.value = null
  message.success(`清空文件成功`)
}

// 下载文件
const handleDownload = async () => {
  downloadPdf(mergedPdf.value, 'unlock.pdf')
}
</script>



<style lang="scss" scoped>
.pageWrap {
  :deep(.ant-upload-wrapper .ant-upload-drag){
    height: auto !important;
  }
  .descArea{
    line-height: 1.6em;
    font-size: 14px;
    color: #666;
    margin-bottom: 12px;
  }
  .btnsWrap{
    margin: 16px 0;
  }
  .resWrap{
    .title{
      margin: 0;
      padding: 12px 0;
      display: flex;
      strong{
        font-size: 18px;
        color: #333;
        flex: 1;
      }
    }
    .res{
      word-break: break-all;
    }
  }
  .inputArea{
    padding: 12px 0 0;
  }
}
</style>